// 云函数入口文件
const cloud = require('wx-server-sdk')
const rp = require('request-promise');
const TcbRouter = require('tcb-router');
const xlsx = require('node-xlsx')
cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
	const app = new TcbRouter({
		event
	})
	app.use(async (ctx, next) => {
		ctx.wxContext = cloud.getWXContext()
		await next()
	});
	app.router('updateUnique', async (ctx, next) => {
		let res = await db.collection(event.table).get()
		let idList = []
		let newData = []
		res.data.map(v => {
			let has = newData.findIndex(e => e.title == v.title)
			idList.push(v._id)
			if (has == -1) {
				delete v._id
				newData.push(v)
			}
		})
		await db.collection(event.table).add({
			data: newData
		})
		await db.collection(event.table).where({
			_id: _.in(idList)
		}).remove()
	})
	app.router('updateLocation', async (ctx, next) => {
		try {
		if ((ctx.wxContext.OPENID ? ctx.wxContext.OPENID : ctx.wxContext.FROM_OPENID) !=
			'oidfu5PLHqjqR8hRzKrufUWXOYlg') return ctx.body = false
		let res = await db.collection('xlsx').where({
			areaCode: ""
		}).skip(0).limit(5).get()
		if (res.errMsg != 'collection.get:ok' || !res.data.length) return ctx.body = false
		let list = res.data.map(async (row, k) => {
			return new Promise(async(resolve, reject) => {
				let resRp = await rp(
					encodeURI(
						`https://apis.map.qq.com/ws/geocoder/v1/?output=json&address=${row.address}&key=YVVBZ-TJK6P-KNBDZ-LWCPA-ZP4SH-G4BMM`
					))
				if (typeof resRp == 'string') {
					resRp = JSON.parse(resRp)
				}
				if (typeof resRp.status != 'undefined' && resRp.status == 0) {
					row.areaCode = resRp.result.ad_info.adcode
					row.region = [
						resRp.result.address_components.province,
						resRp.result.address_components.city,
						resRp.result.address_components.district
					]
					row.location = {
						type: 'Point',
						coordinates: [parseFloat(resRp.result.location.lng),
							parseFloat(resRp.result.location.lat)
						]
					}
					resolve(row)
				} 
			})
		})
		await Promise.all(list).then(async list => {
			if(!Array.isArray(list)) return ctx.body = false
			let idList = []
			list.map(v => {
				idList.push(v._id)
				delete v._id
			})
			let resAdd = await db.collection('xlsx').add({
				data:list
			})
			if(resAdd.errMsg == 'collection.add:ok'){
				await db.collection('xlsx').where({
					_id: _.in(idList)
				}).remove()
			}	
			ctx.body = resAdd.errMsg == 'collection.add:ok' ? true : false
		})
		} catch (err) {
			ctx.body = false
		}
	});
	app.router('uploadExcel', async (ctx, next) => {
		try {
			if (!event.fileID) return ctx.body = false
			let res = await cloud.downloadFile({
				fileID: event.fileID
			})
			var sheets = xlsx.parse(res.fileContent)
			let sheet = sheets[0]['data']
			db.collection('test').add({data:sheet})
			ctx.body = sheet
			return 
			let list = sheet.map(async (row, k) => {
				if (k > 0 && row.length) {
					let telArr = row[1].toString().split('&')
					let obj = {
						_openid: event._openid,
						phone: event.phone,
						title: row[0],
						tel: telArr.length > 1 ? telArr.join(',') : telArr[0],
						address: row[2],
						openTime: row[3],
						remark: row[4],
						infoId: random(1111111111111, 9999999999999).toString(),
						createTime: Date.now(),
						updateTime: Date.now(),
						isUse: 0,
						refuseDesc: "",
						areaCode: "",
						region: [],
						location: {},
					}
					return obj
				}
			})
			await Promise.all(list).then(async list => {
				await cloud.deleteFile({
					fileList: [event.fileID]
				})
				const resAdd = await db.collection(event.table).add({
					data: list
				})
				ctx.body = resAdd.errMsg == 'collection.add:ok' ? true : false
			})

		} catch (err) {
			ctx.body = false
		}
	});

	return app.serve();

}


function random(min, max) {
	if (min >= 0 && max > 0 && max >= min) {
		let gab = max - min + 1;
		return Math.floor(Math.random() * gab + min);
	} else {
		return 0;
	}
}
